<template>
  <div>
    <el-form
      :rules="Rules"
      ref="titleRef"
      label-position="middle"
      :model="formData"
      size="large"
    >
      <el-form-item label="题目主题" prop="topicName">
        <el-input v-model="formData.topicName"></el-input>
      </el-form-item>

      <el-form-item label="题目范围" prop="topicDomain">
        <el-tag
          v-for="tag in tags"
          :key="tag"
          class="mx-1"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}</el-tag
        ><el-input
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          class="ml-1 w-20"
          size="small"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button
          v-else
          class="button-new-tag ml-1"
          size="small"
          @click="showInput"
        >
          + 添加
        </el-button>
      </el-form-item>

      <el-form-item label="题目内容" prop="topicContent">
        <el-input type="textarea" v-model="formData.topicContent"></el-input>
      </el-form-item>

      <el-form-item label="题型" prop="topicType">
        <div>
          <el-radio-group v-model="formData.topicType" size="large">
            <el-radio-button label="single">单选题</el-radio-button>
            <el-radio-button label="mult">多选题</el-radio-button>
            <el-radio-button label="fill">填空题</el-radio-button>'
            <el-radio-button label="judge">判断题</el-radio-button>
            <el-radio-button label="answer">简答题</el-radio-button>
            <el-radio-button label="design">算法设计题</el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>

      <div v-if="formData.topicType == 'judge'">
        <el-form-item label="请选择对错">
          <el-radio-group v-model="formData.topicAnswer">
            <el-radio-button label="A"> True </el-radio-button>
            <el-radio-button label="B"> False </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </div>
      <!-- 单选题 和 多选题 -->
      <div>
        <el-form-item
          label="请输入选项个数"
          v-if="
            formData.topicType != 'fill' &&
            formData.topicType != 'judge' &&
            formData.topicType != 'answer' &&
            formData.topicType != 'design'
          "
          ><el-input-number
            v-model="number"
            :min="1"
            :max="10"
            @change="handleChange"
        /></el-form-item>

        <el-form-item
          prop="topicSelect"
          v-if="
            formData.topicType != 'fill' &&
            formData.topicType != 'judge' &&
            formData.topicType != 'answer' &&
            formData.topicType != 'design'
          "
        >
          <div v-for="i in number" :key="i" style="margin: 20px">
            <el-input
              :placeholder="'请输入选项' + getCharacter(i) + '的内容'"
              v-model="answer[i]"
            ></el-input>
          </div>
        </el-form-item>

        <el-form-item label="请填写答案">
          <el-input
            label="请输入填空项"
            v-model="formData.topicAnswer"
            v-if="
              formData.topicType == 'fill' ||
              formData.topicType == 'answer' ||
              formData.topicType == 'design'
            "
          ></el-input>
          <div v-for="i in number" :key="i">
            <el-radio-group
              v-model="formData.topicAnswer"
              v-if="formData.topicType == 'single'"
            >
              <el-radio-button border="1" :label="getCharacter(i)" />
            </el-radio-group>

            <el-checkbox-group
              v-else-if="formData.topicType == 'mult'"
              v-model="checked[i]"
              @change="test"
            >
              <el-checkbox-button border="1" :label="getCharacter(i)" />
            </el-checkbox-group>
          </div>
        </el-form-item>
      </div>

      <!-- <el-form-item label="选项" prop="topicName">
        <el-input v-model="formData.topicName"></el-input>
      </el-form-item>

      <el-form-item label="答案" prop="topicAnswer">
        <el-input v-model="formData.topicAnswer"></el-input>
      </el-form-item> -->

      <el-form-item label="答案分析" prop="topicKnow">
        <el-input type="textarea" v-model="formData.topicKnow"> </el-input>
      </el-form-item>

      <el-form-item label="难易度" prop="topicHard">
        <div class="demo-rate-block">
          <el-rate v-model="formData.topicHard" :colors="colors"> </el-rate>
        </div>
      </el-form-item>

      <el-form-item label="参考分数" prop="topicScore">
        <div class="demo-rate-block">
          <el-input-number v-model="formData.topicScore" :min="1" :max="10" />
        </div>
      </el-form-item>

      <el-form-item label="上传图片">
        <el-upload
          action
          class="avatar-uploader"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :http-request="httpRequest"
        >
          <img
            v-if="formData.topicImage"
            :src="formData.topicImage"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleAdd(formData)">提交</el-button>
        <el-button type="success" @click="dialogVisible = true"
          >智能识别</el-button
        >
      </el-form-item>

      <el-dialog
        v-model="dialogVisible"
        title="请输入题目与答案,识别内容可能有误"
        width="60%"
        :before-close="handleClose"
      >
        <el-input
          type="textarea"
          v-model="identify"
          sige="large"
          rows="10"
        ></el-input>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleCloseDialog()"
              >识别</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import {
  getCurrentInstance,
  reactive,
  ref,
  nextTick,
  onMounted,
} from "vue-demi";
import { ElInput, ElMessage } from "element-plus";
import { upload } from "../../api/pic";
import { Plus } from "@element-plus/icons-vue";
import { addTopic, getTopicById } from "../../api/topic";

import type {
  UploadFile,
  ElUploadProgressEvent,
  ElFile,
} from "element-plus/es/components/upload/src/upload.type";

//换数据后清空
function radioChange() {
  checked.value = [];
  formData.topicAnswer = "A";
}
function test() {}
const identify = ref("");
const dialogVisible = ref(false);
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const { proxy } = getCurrentInstance();
const tags = ref(["数据结构"]);
const Rules = {
  topicName: [{ required: false, trigger: "blur", message: "请输入标题" }],
  topicType: [{ required: true, trigger: "blur", message: "请选择类型" }],
  topicSelect: [{ required: false, trigger: "blur", message: "请输入选项" }],
  topicContent: [
    { required: true, trigger: "blur", message: "请选择题目内容" },
  ],
};
/**
 * 控制评分颜色
 */
const colors = ref(["#99A9BF", "#F7BA2A", "#FF9900"]); // same as { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }

/**
 * 删除最后那个标签
 */
const handleClose = (tag) => {
  tags.value.splice(tags.value.indexOf(tag), 1);
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    tags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
/**
 * 识别按钮
 */
function handleCloseDialog() {
  console.log("!23");
  /**
   * 看看题目里面有没有这几个开头
   */

  //   if (identify.value.indexOf(canIdentify[i]) != -1) {
  //     console.log("你是这个" + canIdentify[i]);
  //     const temp = identify.value.split(canIdentify[i]);
  //     console.log("分割第一个");
  //     console.log(temp);
  //     const temp2 = temp[1].split("）");
  //     console.log("分割第二个");
  //     console.log(temp2);
  //   }

  const ABC = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
  const canIdentify = [".", "．", "）", ")"];
  const result: Array<String> = [];
  const result2: Array<String> = [];
  for (var i in ABC) {
    for (var j in canIdentify) {
      const temp = ABC[i].concat(canIdentify[j]);
      if (identify.value.indexOf(temp) != -1) {
        result.push(temp);
      }
    }
  }
  console.log(result);
  let temp = identify.value;
  for (var z = 0; z <= result.length; z++) {
    let test = temp.split("" + result[z])[0];
    console.log(test.charAt(test.length - 1));

    if (
      test.charAt(test.length - 1) == "（" ||
      test.charAt(test.length - 1) == "("
    ) {
      test = test.slice(0, test.length - 1);
    }
    result2.push(test);
    if (z != 0) {
      answer.value[z] = result2[z];
    }

    temp = temp.split("" + result[z])[1];
  }
  console.log(result2);
  formData.topicContent = result2[0] + "";
  dialogVisible.value = false;
}
const number = ref(4);
const getInfoBeforeStart = onMounted(() => {
  console.log(proxy.$route.query.id);
  const id = proxy.$route.query.id;
  if (id != null) {
    getTopicById(id).then((res) => {
      console.log(res);

      formData.topicId = res.data.topicId;
      formData.topicName = res.data.topicName;
      formData.topicScore = res.data.topicScore;
      formData.topicImage = res.data.topicImage;
      tags.value = res.data.topicDomain.split("#!");
      formData.topicType = res.data.topicType;
      formData.topicContent = res.data.topicContent;
      formData.topicKnow = res.data.topicKnow;
      formData.topicHard = res.data.topicHard;

      if (res.data.topicType == "single") {
        formData.topicAnswer = res.data.topicAnswer;
      }
      if (res.data.topicType == "mult") {
        checked.value = res.data.topicAnswer.split("#!");
        console.log(checked.value);
      }

      number.value = (res.data.topicSelect.split("#!") as String[]).length;
      //   checked.value = res.data.topicAnswer.split("#!");

      console.log(res.data.topicSelect.split("#!"));

      const tempArray = res.data.topicSelect.split("#!");
      for (var i = 1; i <= res.data.topicSelect.split("#!").length; i++) {
        answer.value[i] = tempArray[i - 1];
      }
    });
  }
});
const answer = ref([]);
const checked = ref([]);
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
const handleChange = (currentValue: number, oldValue: number) => {
  if (currentValue < oldValue) {
    console.log("目前" + currentValue);
    console.log("以前" + oldValue);
    answer.value.pop();
  }
  console.log(currentValue);
};
const handleAvatarSuccess = (res: ElUploadProgressEvent, file: UploadFile) => {
  formData.topicImage = URL.createObjectURL(file.raw);
};
const beforeAvatarUpload = (file: ElFile) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("Avatar picture must be JPG format!");
  }
  if (!isLt2M) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
  }
  return isJPG && isLt2M;
};
const formData = reactive({
  topicId: "",
  topicName: "",
  topicDomain: tags.value.join("#!"),
  topicType: "single",
  topicContent: "",
  topicSelect: "",
  topicAnswer: "A",
  topicKnow: "",
  topicHard: 3,
  topicCreate: "",
  topicScore: 1,
  topicImage: "",
});

function handleAdd(form: any) {
  console.log(formData);

  (proxy.$refs.titleRef as typeof ElInput).validate((valid) => {
    if (!valid) return;
    formData.topicSelect = answer.value.join("#!").slice(2);

    if (formData.topicType == "mult") {
      formData.topicAnswer = checked.value.join("#!");
    }
    formData.topicDomain = tags.value.join("#!");
    addTopic(formData).then((res) => {
      formData.topicId = res.data;
    });
  });
}
function getCharacter(id) {
  return String.fromCharCode(id + 64);
}
/**
 * 上传图片方法
 */
function httpRequest(file) {
  console.log(file);

  const form = new FormData();
  form.append("file", file.file);
  console.log(form);

  upload(form)
    .catch((error) => {
      console.log(error);
    })
    .then((res) => {
      console.log(res);

      formData.topicImage = res.data.url;
    });
}
</script>

<style>
.demo-rate-block {
  padding-top: 0.2rem;
  text-align: center;
  border-right: solid 1px var(--el-border-color-base);
  display: inline-block;

  box-sizing: border-box;
}
.demo-rate-block:last-child {
  border-right: none;
}
.demo-rate-block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>